import {
  Button,
  Checkbox,
  Form,
  Input,
  InputNumber,
  Select,
  Space,
} from "antd";
import { FormItemLayout, FormLayout, useForm } from "antd/es/form/Form";
import type { FormProps } from "antd";
import { getGenderApi } from "../defaultData";
import { useEffect, useState } from "react";

const { Option } = Select;

export interface FormSolutionProps {
  formLayout: FormLayout;
  formItemLayout: FormItemLayout;
}

const initialValues = {
  phoneNumber: 181,
  email: "",
};

type FieldType = {
  username?: string;
  password?: string;
  remember?: string;
  phoneNumber?: number;
  email?: string;
  note?: string;
  gender?: string;
  customizeGender?: string;
};

const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};

const phoneNumberPattern = /^1[3-9]\d{9}$/;
const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

export interface Option {
  label: string;
  value: string;
}

/**
 * 我的表单方案
 */
export const FormSolution = (props: FormSolutionProps) => {
  const { formLayout = "vertical", formItemLayout = "vertical" } = props;
  const [genderOptions, setGenderOptions] = useState<Option[]>([]);

  const mount = async () => {
    const genderRes = await getGenderApi();
    setGenderOptions(genderRes);
  };

  useEffect(() => {
    mount();
  }, []);

  const [form] = useForm();

  /**
   * 表单主体方法
   * @param values
   */
  // 校验结束
  const onFinish: FormProps<FieldType>["onFinish"] = (values) => {
    console.log("Success:", values);
  };

  // 校验失败
  const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (
    errorInfo
  ) => {
    console.log("Failed:", errorInfo);
  };

  // 重置表单
  const onReset = () => {
    form.resetFields();
    console.log(form.getFieldsValue());
  };
  // -------------------------------

  // 表单子元素方法
  const phoneNumberChange = (value: number | null) => {
    if (typeof value === "number") {
      form.setFieldValue("phoneNumber", value);
    }
  };

  const emailChange = (value: string | null) => {
    if (typeof value === "string") {
      form.setFieldValue("email", value);
    }
  };

  const onGenderChange = (value: string) => {
    switch (value) {
      case "male":
        form.setFieldsValue({ note: "Hi, man!", customizeGender: "" });
        break;
      case "female":
        form.setFieldsValue({ note: "Hi, lady!", customizeGender: "" });
        break;
      case "other":
        form.setFieldsValue({ note: "Hi there!" });
        break;
      default:
    }
  };
  // -------------------------------

  return (
    <Form
      {...layout}
      layout={formLayout}
      name="basic"
      labelAlign="left"
      form={form}
      style={{ maxWidth: 600 }}
      colon={false}
      initialValues={initialValues}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      onReset={onReset}
    >
      <Form.Item<FieldType>
        layout={formItemLayout}
        label="Username"
        name="username"
        rules={[
          {
            required: true,
            message: "请输入用户名",
          },
        ]}
      >
        <Input />
      </Form.Item>
      <Form.Item<FieldType>
        layout={formItemLayout}
        label="Password"
        name="password"
        rules={[{ required: true, message: "Please input your password!" }]}
      >
        <Input.Password />
      </Form.Item>
      <Form.Item<FieldType>
        name="remember"
        valuePropName="checked"
        wrapperCol={{
          offset: layout.labelCol.span,
          span: layout.wrapperCol.span,
        }}
      >
        <Checkbox>Remember me</Checkbox>
      </Form.Item>
      <Form.Item
        label="联系电话(正则)"
        name="phoneNumber"
        rules={[
          {
            required: true,
            pattern: phoneNumberPattern,
            message: "手机号格式不正确",
          },
        ]}
        style={{ width: "500px" }}
      >
        <InputNumber
          placeholder={"请输入联系电话"}
          maxLength={11}
          controls={false}
          onChange={phoneNumberChange}
          style={{ width: "200px" }}
        />
      </Form.Item>
      <Form.Item
        label="邮箱(正则)"
        name="email"
        rules={[
          {
            required: true,
            pattern: emailPattern,
            message: "邮箱格式不正确",
          },
        ]}
        style={{ width: "500px" }}
      >
        <Input
          placeholder={"请输入邮箱"}
          onChange={(e) => emailChange(e.target.value)}
          style={{ width: "200px" }}
        />
      </Form.Item>
      <div
        style={{
          border: "1px solid #1677FF",
          borderRadius: "5px",
          // padding: "10px",
          margin: "10px",
        }}
      >
        <h3>表单Item联动</h3>
        <Form.Item name="note" label="Note" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
        <Form.Item name="gender" label="Gender" rules={[{ required: true }]}>
          <Select
            placeholder="Select a option and change input text above"
            onChange={onGenderChange}
            allowClear
          >
            {genderOptions.map((item) => (
              <Option value={item.value}>{item.label}</Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          wrapperCol={{ span: 24 }}
          shouldUpdate={(prevValues, currentValues) =>
            prevValues.gender !== currentValues.gender
          }
        >
          {({ getFieldValue }) =>
            getFieldValue("gender") === "other" ? (
              <Form.Item
                name="customizeGender"
                label="CustomizeGender"
                labelCol={{ span: layout.labelCol.span }}
                wrapperCol={{ span: layout.wrapperCol.span }}
                rules={[{ required: true }]}
              >
                <Input />
              </Form.Item>
            ) : null
          }
        </Form.Item>
      </div>
      <Form.Item {...tailLayout}>
        <Space>
          <Button type="primary" htmlType="submit">
            Submit
          </Button>
          <Button htmlType="button" onClick={onReset}>
            Reset
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
};
